package org.budo.mongo.jdbc.driver;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

import org.budo.jdbc.driver.AbstractBudoJdbcDriver;
import org.budo.jdbc.driver.JdbcUrl;
import org.budo.jdbc.driver.parser.SqlStatementParser;
import org.budo.jdbc.driver.parser.cache.CachedJdbcStatementParser;
import org.budo.mongo.jdbc.driver.parser.jsqlparser.JSqlParserMongoStatementParser;

/**
 * @author li
 * @see com.alibaba.druid.util.JdbcUtils#getDriverClassName
 */
public class BudoMongoJdbcDriver extends AbstractBudoJdbcDriver {
    private static final SqlStatementParser DEFAULT_STATEMENT_PARSER = new CachedJdbcStatementParser() //
            .setStatementParser(new JSqlParserMongoStatementParser());

    public static final String[] URL_PREFIX = { "jdbc:mongo://", "jdbc:mongodb://" };

    public static final Integer DEFAULT_PORT = 27017;

    static {
        try {
            DriverManager.registerDriver(new BudoMongoJdbcDriver());
        } catch (SQLException e) {
            throw new RuntimeException("Can't register driver!", e);
        }
    }

    @Override
    public boolean acceptsURL(String url) throws SQLException {
        return JdbcUrl.acceptsURL(url, URL_PREFIX);
    }

    @SuppressWarnings("resource")
    public Connection connect(String url, Properties info) throws SQLException {
        JdbcUrl jdbcUrl = JdbcUrl.parse(url, URL_PREFIX, DEFAULT_PORT);

        return new BudoMongoJdbcConnection() //
                .jdbcUrl(jdbcUrl) //
                .statementParser(DEFAULT_STATEMENT_PARSER);
    }
}